#include "keyWordCommander.h"

keyWordCommander::keyWordCommander()
{
    dicInit();
}

keyWordCommander::~keyWordCommander()
{

}

void keyWordCommander::printFreq()
{
    for(auto &elem:_freq)
    {
        std::cout<<elem.first<<"  "<<elem.second<<std::endl;
    }
}

void keyWordCommander::printIndex()
{
    for(auto &elem:_index)
    {
        std::cout<<elem.first<<"  ";
        for(auto &x:elem.second)
        {
            std::cout<<x<<" ";
        }
        std::cout<<std::endl;
    }
}


void keyWordCommander::dicInit()
{
    std::string EfreName("../../data/englishDict.dat");
    std::string EindexName("../../data/englishIndex.dat");
    std::string CfreName("../../data/chineseDict.dat");
    std::string CindexName("../../data/chineseIndex.dat");
    
    std::ifstream ifs(EfreName);
    std::string line;
    std::string word;
    int fre;
    while(getline(ifs,line))
    {
        std::istringstream iss(line);
        iss>>word>>fre;
        _freq.push_back(std::make_pair(word,fre));
    }
    ifs.close();

    std::size_t Ecount=_freq.size();
    
    std::ifstream ifs2(CfreName);
    while(getline(ifs2,line))
    {
        std::istringstream iss(line);
        iss>>word>>fre;
        _freq.push_back(std::make_pair(word,fre));
    }
    ifs2.close();

    std::ifstream ifs3(EindexName);
    while(getline(ifs3,line))
    {
        std::istringstream iss(line);
        iss>>word;
        while(iss>>fre)
        {
            _index[word].insert(fre-1);
        }
    }
    ifs3.close();

    std::ifstream ifs4(CindexName);
    while(getline(ifs4,line))
    {
        std::istringstream iss(line);
        iss>>word;
        while(iss>>fre)
        {
            _index[word].insert(Ecount+fre-1);
           // _index[word].insert(fre-1);
        }
    }
    ifs4.close();
}

std::vector<std::string>& keyWordCommander::getKeyWord(std::string &str)
{
    editDistance ed(str);
    WordSegmentation* wd=SingleCut::getInstance();

    vector<std::string> vec1=wd->cutSmall(str,1);
    std::multiset<int> sec;
    for(auto &elem:vec1)
    {
        sec.insert(_index[elem].begin(),_index[elem].end());
    }
    
    std::vector<std::string>* result=new std::vector<std::string>;
    std::multimap<int,std::string,std::less<int>> mec;
    for(auto &x:sec)
    {   
        int dis=ed.distanceEdit(_freq[x].first);
        mec.insert({dis,_freq[x].first});
    }

    int i=0;
    std::unordered_set<string> unsec;
    for(auto &elem:mec)
    {
        if(i>=10)break;
        unsec.insert(elem.second);
        ++i;
    }

    i=0;
    for(auto it=unsec.begin();it!=unsec.end();++it)
    {
        if(i>=5)break;
        result->push_back(*it);
        ++i;
    }
        return *result;
}

